package com.yangfei.mystudy1020.OGL20.utils;

import android.util.Log;

import static android.opengl.GLES20.*;

/**
 * Created by yangfei on 2017/12/12.
 */

public class ShaderHelper {
    public static int compileVertexShader(String shaderCode){
        return compileShader(GL_VERTEX_SHADER,shaderCode);
    }

    public static int compileFragmentShader(String shaderCode){
        return compileShader(GL_FRAGMENT_SHADER,shaderCode);
    }

    public static int compileShader(int type,String shaderCode){
        final int shaderObjectId = glCreateShader(type);

        if(shaderObjectId == 0){
            Log.e("ShaderHelper","could not create new shader");
        }

        glShaderSource(shaderObjectId,shaderCode);
        glCompileShader(shaderObjectId);

        final int[] compileStatus = new int[1];
        glGetShaderiv(shaderObjectId,GL_COMPILE_STATUS,compileStatus,0);
        Log.e("ShaderHelper","results of compiling source:"+"\n"
                +shaderCode+"\n:"
                +glGetShaderInfoLog(shaderObjectId));

        if(compileStatus[0] == 0){
            glDeleteShader(shaderObjectId);

            Log.e("ShaderHelper","compile of shader failed.");

            return 0;
        }
        return shaderObjectId;
    }

    public static int linkProgram(int vertexShaderId,int fragmentShaderId){
        final int programObjectId = glCreateProgram();

        if(programObjectId == 0){
            Log.e("ShaderHelper","could not create new program");
        }

        glAttachShader(programObjectId,vertexShaderId);
        glAttachShader(programObjectId,fragmentShaderId);

        glLinkProgram(programObjectId);

        final int[] linkStatus = new int[1];
        glGetProgramiv(programObjectId,GL_LINK_STATUS,linkStatus,0);
        Log.e("ShaderHelper","results of linking program:\n"+glGetProgramInfoLog(programObjectId));

        if(linkStatus[0] == 0){
            glDeleteShader(programObjectId);
            Log.e("ShaderHelper","linking of program failed");
        }

        return programObjectId;
    }

    public static boolean validateProgram(int programObjectId){
        glValidateProgram(programObjectId);

        final int[] validateStatus = new int[1];
        glGetProgramiv(programObjectId,GL_VALIDATE_STATUS,validateStatus,0);
        Log.e("ShaderHelper","results of validating program: "+validateStatus[0]
                +"\nLog:"+glGetProgramInfoLog(programObjectId));
        return validateStatus[0]!=0;
    }
}
